/**
 * desc：  权限标识管理
 * author：DestinyJun
 * date：  2020/4/21 17:01
 */
import React, {Component} from 'react';
import 'moment/locale/zh-cn'; // 这两个他妈的要放在最前面引入，日龙
import locale from 'antd/es/date-picker/locale/zh_CN'; // 这两个他妈的要放在最前面引入，日龙
import './CountyRate.scss';
import {Button, DatePicker, Form, InputNumber, Modal, Select, Space, Table, Tree, Pagination} from "antd";
import {post} from "../../service/Interceptor";
import {FlinkTypeApi, RuleActionApi, RuleApi} from "../../service/Apis";
import {ModalHeader} from "../../components/ModalHeader";
import {reverseTree, transformTree} from "../../service/tools";
import moment from "moment/moment";
const { Option } = Select;


export class CountyRate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rule_action_list: [],
      rule_action_visible: false,
      rule_action_loading: false,
      rule_action_id: null,
      area_tree: [],

      rule_tree_visible: false,
      rule_tree_name: '点击选择区域',

      rule_tree_filter_visible: false,
      rule_tree_filter_name: '点击选择区域',

      flink_type_list: [],
      flink_pageNo: 1,
      flink_totalPage: 0,

      disease_id:  null,
      happening_date:  null,
      area_id:  null,
    };
    // 表单模型
    this.rule_action_formRef = React.createRef();
    // 表头信息定义
    this.rule_action_column = [
      {
        title: '传染病',
        dataIndex: 'disease_name',
      },
      {
        title: '所属区域',
        dataIndex: 'area_name',
      },
      {
        title: '区域级别',
        dataIndex: 'leve',
      },
      {
        title: '所属父区域',
        dataIndex: 'parent_name',
      },
      {
        title: '转阳率（%）',
        dataIndex: 'positive_rate',
      },
      {
        title: '统计时间',
        dataIndex: 'happening_date',
      },
      {
        title: '报警时间',
        dataIndex: 'create_time',
      },
      {
        title: '操作',
        render: (item) => {
          return(
            <Space size="middle">
              <Button type={'primary'} style={{background: '#00E3CA',borderColor: '#00E3CA'}} onClick={this.ruleActionUpdate.bind(this,item)}>编辑</Button>
              <Button type={'primary'} danger onClick={this.ruleActionDel.bind(this,item)}>删除</Button>
            </Space>
          )
        },
      }
    ]
    // 校验信息定义
    this.rule_action_validateMessages = {
      required: '${label}是必填项!',
      types: {
        number: '${label}必须是数字',
      },
    };
    this.area_id = null;
  }
  componentDidMount() {
    this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id);
    // 初始化树结构
    post(RuleApi.GET_RULE_TREE, {})
      .then(res => {
        this.setState({
          area_tree: transformTree(reverseTree( res.data).map(item => ({...item,key: item.id}))),
        })
      })
    post(FlinkTypeApi.GET_FLINK_TYPE, {})
      .then(res => {
        this.setState({
          flink_type_list: res.data.map(item => ({...item,key: item.id})),
        })
      })
  }
  // 初始化
  ruleActionInit(pageNo,disease_id,happening_date,area_id) {
    post(
      RuleActionApi.GET_RULE_ACTION, {pageNo,pageSize: 8,disease_id,happening_date,area_id})
      .then(res => {
        this.setState({
          rule_action_list: res.data.map(item =>({...item,key: item.id})),
          rule_action_visible: false,
          flink_totalPage: res.totalRecord,
        })
      })

  }
  // 添加/修改
  ruleActionSave () {
    let url,data;
    if (!this.state.rule_action_id) {
      url = RuleActionApi.ADD_RULE_ACTION;
      data = this.rule_action_formRef.current.getFieldsValue()
    } else {
      url = RuleActionApi.UPDATE_RULE_ACTION;
      data = this.rule_action_formRef.current.getFieldsValue();
      data['id'] = this.state.rule_action_id;
    }
    data.happening_date = moment(data.happening_date).format('YYYY-MM')
    post(url, data)
      .then(() => {
        this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id);
      })
      .catch(err => {})
  }
  // 删除
  ruleActionDel (item) {
    if (window.confirm('确定要删除么?')) {
      post(RuleActionApi.DEL_RULE_ACTION, {id: item.id})
        .then(() => {
          this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id);
        })
        .catch(err => {})
    }
  }
  // 修改
  ruleActionUpdate(item) {
    this.setState({
      rule_action_visible: true,
      rule_action_id: item.id,
      rule_tree_name: item.area_name
    },() => {
      this.rule_action_formRef.current.setFieldsValue({
        area_id: item.area_id,
        disease_id: item.disease_id,
        positive_rate: item.positive_rate,
        happening_date: moment(item.happening_date, 'YYYY-MM')
      })
    })
  }
  // render渲染
  render() {
    return (
      <div className={'ruleAction'}>
        <h2 className="rule-action-title">转阳率管理</h2>
        <div className="rule-action-btn">
          <Button type={'primary'} onClick={() => this.setState({rule_action_visible: true,rule_action_id: null})}>转阳率添加</Button>
          <Select
            style={{width: '10%',marginLeft: '15px'}}
            placeholder={'点击选择传染病'}
            value={this.state.disease_id}
            notFoundContent={<span>暂无内容</span>}
            onChange={(res) => {
              this.setState({
                flink_pageNo: 1,
                disease_id: res,
              },() => {this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id)})
            }}
          >
            {
              this.state.flink_type_list.length > 0 &&
              this.state.flink_type_list.map((item,index) => (<Option key={`flink_${index}`} value={item.id}>{item.disease_name}</Option>))
            }
          </Select>
          <DatePicker
            value={this.state.happening_date?moment(this.state.happening_date):null}
            locale={locale} placeholder={'请选择统计日期'} picker="month"
            style={{width: '10%',marginLeft: '15px'}}
            onChange={(time) => {
              this.setState({
                flink_pageNo: 1,
                happening_date: moment(time).format('YYYY-MM'),
              },() => {this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id)})
            }}
          />
          <Button
            type="primary" ghost block
            style={{width: '10%',marginLeft: '15px',borderColor: '#D9D9D9',textAlign: 'left',color: '#262626',padding: '4px 10px'}}
            onClick={() => {
            this.setState({rule_tree_filter_visible: true});
            }}
          >
            {
              this.state.rule_tree_filter_name === '点击选择区域'?
                <span style={{color: '#BFBFBF'}}>{this.state.rule_tree_filter_name}</span>:
                this.state.rule_tree_filter_name
            }
          </Button>
          <Button type={'primary'} onClick={() => {
            this.setState({
              flink_pageNo: 1,
              disease_id: null,
              happening_date: null,
              area_id: null,
              rule_tree_filter_name: '点击选择区域',
            },() => {
              this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id);
            })
          }} style={{marginLeft: '15px'}}>重置</Button>
        </div>
        <div className="rule-action-table">
          {
            this.state.rule_action_list.length>0 &&  <Table
              columns={this.rule_action_column}
              pagination={false}
              scroll={{ y: '63vh' }}
              dataSource={this.state.rule_action_list}
            />
          }
          <Pagination
            hideOnSinglePage={true}
            showSizeChanger={false}
            pageSize={8} style={{marginTop: '5px'}}
            defaultCurrent={this.state.flink_pageNo}
            onChange={(num) => {
              this.setState({
                flink_pageNo: num
              },() => {
                this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id);
              })
            }}
            total={this.state.flink_totalPage} />
        </div>
        <div className="rule-action-modal">
          {/*form弹窗*/}
          <Modal
            title={<ModalHeader title={'转阳率操作'} />}
            closable={false}
            visible={this.state.rule_action_visible}
            centered
            okText={'确认'}
            afterClose={() => {
              this.rule_action_formRef.current.resetFields();
              this.setState({
                rule_action_visible: false,
                rule_tree_name: '点击选择区域',
              })
            }}
            onOk={() => {
              this.rule_action_formRef.current.submit()
            }}
            confirmLoading={this.state.rule_action_loading}
            cancelText={'取消'}
            onCancel={() => this.setState({rule_action_visible: false})}
          >
            <Form
              ref={this.rule_action_formRef}
              name={'form'}
              validateMessages={this.rule_action_validateMessages}
              labelCol={{span: 6}}
              wrapperCol={{span: 16}}
              onFinish={this.ruleActionSave.bind(this)}
              initialValues={{
                area_id: null,
                leve: null,
                disease_id: null,
                positive_rate: null,
                happening_date: null,
              }}
            >
              <Form.Item label="所属区域" >
                <Button type="primary" onClick={() => {
                  this.setState({rule_tree_visible: true});
                }}
                        style={{borderColor: '#D9D9D9',textAlign: 'left',color: '#262626',padding: '4px 10px'}} ghost block>
                  {
                    this.state.rule_tree_name === '点击选择区域'?
                      <span style={{color: '#BFBFBF'}}>{this.state.rule_tree_name}</span>:
                      this.state.rule_tree_name
                  }
                </Button>
                <Form.Item name="area_id" noStyle >
                  <InputNumber placeholder={'请选择区域'} style={{display: 'none'}} />
                </Form.Item>
              </Form.Item>
              <Form.Item label="传染病" name="disease_id" rules={[{required: true}]}>
                <Select placeholder={'点击选择传染病'} notFoundContent={<span>暂无内容</span>}>
                  {
                    this.state.flink_type_list.length > 0 &&
                    this.state.flink_type_list.map((item,index) => (<Option key={`flink_${index}`} value={item.id}>{item.disease_name}</Option>))
                  }
                </Select>
              </Form.Item>
              <Form.Item label="转阳率" name="positive_rate" rules={[{required: true}]}>
                <InputNumber placeholder={'请输入转阳率'} style={{width: '100%'}} rules={[{types: 'number'}]} />
              </Form.Item>
              <Form.Item label="统计日期" name="happening_date" rules={[{required: true}]}>
                <DatePicker locale={locale} placeholder={'请选择统计日期'} picker="month" style={{width: '100%'}} />
              </Form.Item>
            </Form>
          </Modal>
          {/*区域树弹窗*/}
          <Modal
            destroyOnClose={true}
            title={<ModalHeader title={'区域选择'} />}
            width={'30vw'}
            centered
            closable={false}
            visible={this.state.rule_tree_visible}
            footer={<Button type="primary" ghost danger  onClick={() => this.setState({rule_tree_visible: false})}>关闭</Button>}
            onCancel={() => this.setState({rule_tree_visible: false})}
          >
            <div className={'rule-tree-box'}>
              <Tree
                showLine={true}
                onSelect={(key,info) => {
                  this.setState({
                    rule_tree_visible: false,
                    rule_tree_name: info.selectedNodes[0].area_name,
                  })
                  this.rule_action_formRef.current.setFieldsValue({area_id: info.selectedNodes[0].id})
                  this.rule_action_formRef.current.setFieldsValue({leve: info.selectedNodes[0].leve})
                }}
                titleRender={(nodeData) => {
                  return (<span>{nodeData.area_name}</span>)
                }}
                treeData={this.state.area_tree}
              />
            </div>
          </Modal>
          {/*筛选*/}
          <Modal
            destroyOnClose={true}
            title={<ModalHeader title={'区域筛选'} />}
            width={'30vw'}
            centered
            closable={false}
            visible={this.state.rule_tree_filter_visible}
            footer={
              <>
                <Button type="primary" ghost danger  onClick={() => this.setState({rule_tree_filter_visible: false})}>关闭</Button>
              </>
            }
            onCancel={() => this.setState({rule_tree_filter_visible: false})}
          >
            <div className={'rule-tree-box'}>
              <Tree
                showLine={true}
                onSelect={(key,info) => {
                  this.setState({
                    flink_pageNo: 1,
                    area_id: info.selectedNodes[0].id,
                    rule_tree_filter_visible: false,
                    rule_tree_filter_name: info.selectedNodes[0].area_name
                  },() => {
                    this.ruleActionInit(this.state.flink_pageNo,this.state.disease_id,this.state.happening_date,this.state.area_id);
                  })
                }}
                titleRender={(nodeData) => {
                  return (<span>{nodeData.area_name}</span>)
                }}
                treeData={this.state.area_tree}
              />
            </div>
          </Modal>
        </div>
      </div>
    );
  }
}
